<?php


namespace addons\facrm\library\queue;

use app\common\library\Sms;
use think\Log;
use think\queue\job;
use think\Validate;

/**
 * 批量发送短息队列
 * Class SmssJob
 * @package addons\facrm\library\queue
 */
class SmssJob
{
    /**
     * @param job $job
     * @param $data ['types'] //发送配置，types：customer，contacts
     * @param $data ['typesid'] //对象集合ID，多个以逗号隔开
     * @param $data ['content'] //短息预览
     * @param $data ['create_user_id'] //发送人ID
     * @param $data ['record_type'] //跟进类型ID
     * @param $data ['sms_id'] //短息模板ID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fire(Job $job, $data)
    {
        if ($job->attempts() > 3) {
            //通过这个方法可以检查这个任务已经重试了几次了
            $job->delete();
            return;
        }
        $types_data = array();//发送对象数据，如客户，联系人
        if ($data && $data['types']) {
            switch ($data['types']) {
                case "customer":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->where('id', 'in', $data['typesid'])->select();
                    break;
                case "contacts":
                    $contactsModel = new \app\admin\model\facrm\customer\Contacts();
                    $types_data = $contactsModel->where('id', 'in', $data['typesid'])->select();
                    break;
                case "clues":
                    $custModel = new \app\admin\model\facrm\Clues();
                    $types_data = $custModel->where('id', 'in', $data['typesid'])->select();
                    break;
                default:
                    break;
            }
        }
        if (!$types_data || !$data['sms_id']) { //不存在发送对象信息和短息模板就返回
            $job->delete();
            return true;
        }
        //模板配置
        $config_row = (new \app\admin\model\facrm\Setting())->where('key', "sms_tpl_setting_lists")->find($data['sms_id']);
        if (!$config_row) {
            $job->delete();
            return false;
        }

        $config_row['values'] = json_decode($config_row['values'], true);
        $tpl = $config_row['values'];
        $tpl['content'] = is_array($tpl['content']) ? $tpl['content'] : (array)json_decode($tpl['content'], true);

        foreach ($types_data as $row) {
            if (!empty($row['mobile'])) {
                if (!Validate::is($row['mobile'], "/^1[3456789]{1}\d{9}$/")) {
                    continue;//不存在邮箱下一步
                }

                //封装msg
                $temp_val = array();
                foreach ($tpl['content'] as $item) {
                    if ($item['value']) {
                        $value = $item['key'] == 'diy_text' ? $item['def_val'] : '';
                        $value = (isset($types_data[$item['key']]) && $types_data[$item['key']] && !$value ? $types_data[$item['key']] : $item['def_val']);
                        $temp_val[$item['value']] = $value;
                    }
                }

                //短息发送
                $result = Sms::notice($row['mobile'], $temp_val, $config_row['values']['tpl_id']);
                if ($result){
                    //param_data types类型如customer,contacts| typesid对应的ID
                    //send_data发送的内容
                    //types_data 当前对象的数据
                    $row['create_user_id'] = $data['create_user_id'];//用于标明是谁发送的
                    $row['record_type']=$data['record_type'];
                    $row['content'] = __($tpl['tpl_content'], $temp_val);//处理之后的模板数据

                    $data['typesid']=$row->id;//因为参数需要多个，批量发送的多个ID，所以处理一下。

                    hook("facrm_send_sms_success", array(
                        'param_data' => $data,
                        'send_data' =>$row,
                        'types_data' => $types_data
                    )
                    );
                }


            }
        }
        $job->delete();
        return true;
    }

    public function failed($data)
    {
        Log::write("短息任务失败：" . print_r(['data' => $data,], true), 'error');
    }

}